/**
 * @ClassName: UserCartUtils
 * @author linsen
 * @date 2016-10-11
 */
package com.fzrskj.cloud.free.user.utils;

import com.fzrskj.cloud.free.core.enums.CartTypeEnum;
import com.fzrskj.cloud.free.core.enums.PriceTypeEnum;
import com.fzrskj.cloud.free.core.enums.ProductTypeEnum;
import com.fzrskj.cloud.free.core.tool.CDateTimeTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.dic.utils.DicPriceDiyUtils;
import com.fzrskj.cloud.free.sys.utils.SysProductPriceUtils;
import com.fzrskj.cloud.free.user.bean.UserAccount;
import com.fzrskj.cloud.free.user.bean.UserCart;
import com.fzrskj.cloud.free.user.bean.UserCartView;
import com.fzrskj.cloud.free.user.bean.UserOrder;
import com.fzrskj.cloud.free.user.dao.UserCartDao;
import com.winiis.component.common.utils.tool.CSysTool;
import ms.core.consts.SysErr;
import ms.core.object.CObject;
import ms.core.tool.StrTool;
import net.sf.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.*;

public class UserCartUtils extends CObject{

	/**
	 * 添加购物车(域名开通和续费)
	 * @param userCart
	 * @return int
	 */
	public int addUserCart(UserCart userCart){
		double price=0;
		UserAccountUtils uaUtils = new UserAccountUtils();
		UserAccount ua = uaUtils.queryUserAccountByUid(userCart.getUserId());
		Map<String,Object> cdt = new HashMap<String, Object>();
		cdt.put("productCode", userCart.getProductCode());
		cdt.put("levelCode", ua.getLevelCode());

		//注册/续费
		if(userCart.getCartType().equals("add")) {
			cdt.put("chargeId", 1);
		} else if(userCart.getCartType().equals("renew")) {
			cdt.put("chargeId", 2);
		}

		int ret = 0;
		int applyTime = userCart.getApplyTime();

		SysProductPriceUtils sppUtils = new SysProductPriceUtils();

		if (ProductTypeEnum.DOMAIN.getTag().equals(userCart.getProductClass())){
			cdt.put("regType", userCart.getRegType());
			cdt.put("productClass", userCart.getProductClass());
			price = sppUtils.getDomainProductPrice(applyTime, cdt);
		} else {
			price = sppUtils.getProductPrice(applyTime, cdt);
		}
		if(price > 0){
			userCart.setTotalPrice(price);
			userCart.setPrice(price);
			ret = addUserCartRecord(userCart);
		}else{
			this.setErrCode(SysErr.CODE_FAILURE, "获取产品价格失败");
		}
		return ret;
	}

	/**
	 * 添加到购物车（自定义产品）
	 * @param userCart
	 * @return
	 */
	public Integer addUserCartDiy(UserCart userCart){
		JSONObject json = null;
		Map<String,Object> cdt = new HashMap<String, Object>();
		cdt.put("productClass", userCart.getProductClass());
		cdt.put("productCode", userCart.getProductCode());

		//云主机计费
		json = JSONObject.fromObject(userCart.getProductParam());
		cdt.put("hostType", ProductTypeEnum.DIY.getTag());
		cdt.put("applyTime", userCart.getApplyTime());
		cdt.put("priceType", userCart.getPriceType());
		cdt.put("num", 1);
		cdt.put("userId", userCart.getUserId());
		cdt.put("chargeId", CartTypeEnum.RENEW.equals(userCart.getCartType()) ? 2 : 1);
		cdt.put("updateServerType", json.get("updateServerType"));
		if (json.containsKey("diy_params")) {
			cdt.putAll(json.getJSONObject("diy_params"));
			cdt.put("number", 1);
		}
		if (json.containsKey("webId")){
			cdt.put("webId", json.get("webId"));
		}
		if (json.containsKey("id")){
			cdt.put("id", json.get("id"));
		}
		DicPriceDiyUtils diyUtils = new DicPriceDiyUtils();
		JSONObject map = new JSONObject();
		if (CartTypeEnum.ADD.equals(userCart.getCartType())) {
			map = JSONObject.fromObject(diyUtils.getPrice(cdt));
		} else if (CartTypeEnum.RENEW.equals(userCart.getCartType())) {
			map = JSONObject.fromObject(diyUtils.getPrice(cdt));
		}

		//TODO：是否有附加参数
		json.put("num", 1);

		JSONObject priceMap = map.getJSONObject("data");

		userCart.setProductParam(json.toString());
		userCart.setTotalPrice(Double.parseDouble(priceMap.getString("totalPrice")));
		userCart.setPrice(Double.parseDouble(priceMap.getString("payPrice")));
		int ret=addUserCartRecord(userCart);
		return ret;
	}

	/**
	 * 添加购物车记录
	 * @param userCart
	 * @return int
	 */
	public int addUserCartRecord(UserCart userCart){
		UserCartDao dao =  new UserCartDao();
		int ret = dao.addUserCart(userCart);
		String code = dao.getErrCode();
		this.setErrCode(code);
		dao.dispose();
		return ret;
	}

	//获取购物车列表
	public List<UserCartView> getUserCartList(Map<String, Object> cdt){
		UserCartDao dao=new UserCartDao();
		List<UserCartView> list = dao.getUserCartList(cdt);
		String code = dao.getErrCode();
		this.setErrCode(code);
		dao.dispose();
		return list;
	}

	//删除购物车
	public int delUserCart(int userId,String cartNos){
		List<String> list=new ArrayList<String>();
		String[] arr=cartNos.split(",");
		for(String str:arr){
			list.add(str);
		}

		UserCartDao dao=new UserCartDao();
		int ret=dao.delUserCart(userId, list);
		String code = dao.getErrCode();
		this.setErrCode(code);
		dao.dispose();
		return ret;
	}

	//修改购物车
	public int modUserCart(Map<String, Object> values, Map<String, Object> cdt){
		double price=0;
		UserCartDao dao=new UserCartDao();
		UserCart userCart=dao.getUserCart(cdt.get("cartNo").toString());
		if(userCart==null) {
			return 0;
		}

		String productParam = userCart.getProductParam();
		Map<String,Object> obj = new HashMap<>();
		obj.put("productClass", userCart.getProductClass());
		obj.put("productCode", userCart.getProductCode());
		obj.put("hostType", userCart.getRegType());
		obj.put("cartType", userCart.getCartType());
		if (userCart.getCartType().equals("add")) {
			obj.put("buyOperation", 1);
		} else if (userCart.getCartType().equals("renew")) {
			obj.put("buyOperation", 2);
		} else if (userCart.getCartType().equals("update")) {
			obj.put("buyOperation", 3);
		} else  {
			obj.put("buyOperation", -1);
		}
		if (ProductTypeEnum.DIY.getTag().equals(userCart.getProductClass())) {
			JSONObject json = JSONObject.fromObject(productParam);
			obj.put("applyTime", values.get("applyTime"));
			obj.put("priceType", values.get("priceType"));
			obj.put("userId", userCart.getUserId());
			obj.put("num", json.get("num"));
			if(userCart.getCartType().equals("add")) {
				obj.put("chargeId", 1);
			} else if(userCart.getCartType().equals("renew")) {
				obj.put("chargeId", 2);
				obj.put("id", json.get("id"));
			}

			JSONObject diyParams;
			if (json.containsKey("diy_params")) {
				diyParams = json.getJSONObject("diy_params");
			}else{
				diyParams =  new JSONObject();
			}
			diyParams.put("number", json.get("num"));
			diyParams.put("period", values.get("applyTime"));
			diyParams.put("period_unit", PriceTypeEnum.MONTH.equals(values.get("priceType").toString()) ? "month" : "year");
			obj.putAll(diyParams);
			DicPriceDiyUtils diyUtils = new DicPriceDiyUtils();
			JSONObject map = JSONObject.fromObject(diyUtils.getPrice(obj));
			JSONObject priceMap = map.getJSONObject("data");

			json.put("diy_params", diyParams);
			values.put("productParam", json.toString());
			values.put("price", priceMap.getString("payPrice"));
			values.put("totalPrice", priceMap.getString("totalPrice"));
		}

		int ret=dao.modUserCart(values, cdt);
		String code = dao.getErrCode();
		this.setErrCode(code);
		dao.dispose();
		return ret;
	}

	//修改购物车域名注册商 add wzj by 2019-01-14
	public int modUserCartDomainRegtype(Map<String, Object> values, Map<String, Object> cdt){
		UserCartDao dao = new UserCartDao();
		UserCart userCart = dao.getUserCart(cdt.get("cartNo").toString());
		if(userCart == null) {
			this.setErrCode(SysErr.SYS_DATA_NOT_FOUND);
			return 0;
		}
		if( !ProductTypeEnum.DOMAIN.getTag().equals(userCart.getProductClass())) {
			this.setErrCode(SysErr.SYS_DATA_NOT_FOUND);
			return  0;
		}

		int ret=dao.modUserCart(values, cdt);
		String code = dao.getErrCode();
		this.setErrCode(code);
		dao.dispose();
		return ret;
	}

	//统计总价格
	public double countTotalPrice(int userId,String cartNos){
		double totalPrice = 0;
		String[] arr = cartNos.split(",");

		Map<String, Object> cdt = new HashMap<String, Object>();
		cdt.put("userId", userId);
		UserCartDao dao = new UserCartDao();
		List<UserCartView> list = dao.getUserCartList(cdt);
		for (int i = 0; i < list.size(); i++) {
			for (int j = 0; j < arr.length; j++) {
				if (list.get(i).getCartNo().equals(arr[j])) {
					totalPrice += list.get(i).getPrice();
					continue;
				}
			}
		}
		dao.dispose();
		return totalPrice;
	}

	//获取第一个域名订单的注册商
	public int getDomainCartRegType(int userId,String cartNos){
		int regType = 0;
		String[] arr=cartNos.split(",");

		Map<String, Object> cdt=new HashMap<String, Object>();
		cdt.put("userId", userId);
		UserCartDao dao=new UserCartDao();
		List<UserCartView> list=dao.getUserCartList(cdt);
		dao.dispose();
		for(int i=0;i<list.size();i++){
			for(int j=0;j<arr.length;j++){
				if(list.get(i).getCartNo().equals(arr[j])){
					if ("domain".equals(list.get(i).getProductClass())){
						regType =  Integer.valueOf(list.get(i).getRegType());
						break;
					}
				}
			}
		}
		return regType;
	}

	//获取购物车购买列表
	public List<UserCart> getUserCartBuyList(int userId,String cartNos){
		List<String> list=new ArrayList<String>();
		String[] arr=cartNos.split(",");
		for(String str:arr){
			list.add(str);
		}

		UserCartDao dao=new UserCartDao();
		List<UserCart> userCartList=dao.getUserCartBuyList(userId, list);
		String code = dao.getErrCode();
		this.setErrCode(code);
		dao.dispose();
		return userCartList;
	}

	//修改购物车信息
	public int upDomainUserCart(Map<String, Object> values, Map<String, Object> cdt){
		UserCartDao dao=new UserCartDao();
		int ret=dao.modUserCart(values, cdt);
		String code = dao.getErrCode();
		this.setErrCode(code);
		dao.dispose();
		return ret;
	}

	/**
	 * 查询逾期多少天的数据
	 * @param expiryDays
	 * @return
	 */
	public List<UserCart> arrearsUserCart(int expiryDays){
		UserCartDao dao = new UserCartDao();
		String str = CDateTimeTool.getDivDay(new Date(), expiryDays-expiryDays*2);
		String addTime = CDateTimeTool.getDivDay(new Date(), expiryDays-expiryDays*2+1);
		List<UserCart> rets = dao.arrearsUserCart(str,addTime);
		this.setErrCode(dao.getErrCode());
		dao.dispose();
		return rets;
	}

	/**
	 * 查询到期未生成订单
	 * @param dateTime
	 * @return
	 */
	public List<UserCart> queryExpireNoBuildOrder(String dateTime){
		UserCartDao dao = new UserCartDao();
		List<UserCart> rets = dao.queryExpireNoBuildOrder(dateTime);
		this.setErrCode(dao.getErrCode());
		dao.dispose();
		return rets;
	}

	/**
	 * 根据userName查询所持有的购物车数量
	 * @param userName
	 * @return
	 */
	public int queryUserCartCount(String userName){
		UserCartDao dao = new UserCartDao();
		Map<String,Object> cdt = new HashMap<String, Object>();
		cdt.put("userName", userName);
		int queryUserCartCount = dao.queryUserCartCount(cdt);
		this.setErrCode(dao.getErrCode());
		dao.dispose();
		return queryUserCartCount;
	}

	/**
	 * 根据cartNo删除数据
	 * @param cartNo
	 * @return
	 */
	public int delUserCart(String cartNo){
		Map<String,Object> cdt = new HashMap<String, Object>();
		cdt.put("cartNo", cartNo);
		UserCartDao dao = new UserCartDao();
		int ret=dao.delUserCart(cdt);
		String code = dao.getErrCode();
		this.setErrCode(code);
		dao.dispose();
		return ret;
	}

	/**
	 * 根据用户名与参数查询购物车
	 * @param userName
	 * @param productParam
	 * @return
	 */
	public List<UserCart> queryCart(String userName,String productParam,String cartType){
		UserCartDao dao = new UserCartDao();
		List<UserCart> queryCart = dao.queryCart(userName, productParam,cartType);
		String code = dao.getErrCode();
		this.setErrCode(code);
		dao.dispose();
		return queryCart;
	}

	/**
	 * 查询购物车符合条件的数量
	 * @param cdt
	 * @return
	 */
	public int queryUserCartExistCount(Map<String, Object> cdt){
		UserCartDao dao = new UserCartDao();
		int count = dao.queryUserCartExistCount(cdt);
		this.setErrCode(dao.getErrCode());
		dao.dispose();
		return count;
	}

	/**
	 * 是否超出限制.
	 * @return boolean.
	 */
	public Boolean isOutOffLimit() {
		String cartMaxNum= DicParamUtils.getParamValue("cartMaxNum");
		if(!StrTool.isBlankStr(cartMaxNum)){
			String userName = CloudContextUtils.getSession().getUname();
			UserCartUtils userCartUtils = new UserCartUtils();
			int count = userCartUtils.queryUserCartCount(userName);
			if(count>=Integer.valueOf(cartMaxNum)){
				this.setErrCode("OUT_OFF_LIMIT", "购物车数量已超过规定数【最大："+cartMaxNum+"】，请先处理！");
				return true;
			}
		}
		return false;
	}

	/**
	 * 计算域名首年价格(域名开通和续费)
	 * @param userOrder
	 * @return int
	 * add by hl831 wzj 2019/08/02
	 */
	public static int queryUserOrderDomainFirstYearPrice(UserOrder userOrder){
		int price = 0;
		int applyTime = 1;
		UserAccountUtils uaUtils = new UserAccountUtils();
		SysProductPriceUtils sppUtils = new SysProductPriceUtils();
		do {
			if (userOrder == null){
				price = -1;
				break;
			}
			if (!ProductTypeEnum.DOMAIN.getTag().equals(userOrder.getProductClass())){
				price = -1;
				break;
			}
			UserAccount ua = uaUtils.queryUserAccountByUid(userOrder.getUserId());
			if (ua ==  null){
				price = -1;
				break;
			}

			Map<String, Object> cdt = new HashMap<>();
			cdt.put("productCode", userOrder.getProductCode());
			cdt.put("levelCode", ua.getLevelCode());

			//注册/续费
			if (userOrder.getOrderType().equals("add")) {
				cdt.put("chargeId", 1);
			} else if (userOrder.getOrderType().equals("renew")) {
				cdt.put("chargeId", 2);
			}
			cdt.put("regType", userOrder.getRegType());
			cdt.put("productClass", userOrder.getProductClass());
			price = sppUtils.getDomainProductPrice(applyTime, cdt);

		} while (false);
		uaUtils.dispose();
		sppUtils.dispose();
		return price;
	}

	public String createCartNO() {
		return createCartNO("C");
	}

	/**
	 * 生成购物车编号
	 * @param pre
	 * @return
	 */
	public String createCartNO(String pre) {
		return pre + new SimpleDateFormat("yyyyMMdd").format(new Date()) + CSysTool.getRandomNum(100000, 999999);
	}
}
